﻿using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core.Events;
using System;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using WPFExcelReport.Helpers;
using System.Windows.Threading;
using System.Threading;
namespace WPFExcelReport
{

    public partial class ViewBase : ContentControl, IDisposable
    {
        #region ==dwMaster===========
        public static readonly DependencyProperty dwMasterProperty = DependencyProperty.Register("dwMaster",
            typeof(DataRow), typeof(ViewBase),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OndwMasterChanged));
        public DataRow dwMaster
        {
            get
            {
                DataRow row = (DataRow)GetValue(dwMasterProperty);
                if (row == null)
                {
                    MV = (ViewModelBase)DataContext;
                    if (MV != null)
                    {
                        row = MV.dwMaster;
                    }
                }
                return row;
            }
            set
            {
                SetValue(dwMasterProperty, value);
                OnMasterChg(value);
            }
        }
        private static void OndwMasterChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as ViewBase;
            if (src != null)
            {
                src.dwMaster = (DataRow)e.NewValue;
            }
        }
        public virtual void OnMasterChg(DataRow _dwMaster)
        {
            if (MV == null)
                return;
            MV.dwMaster = _dwMaster;
        }
        #endregion
        #region ==dwDetail===========
        public static readonly DependencyProperty dwDetailProperty = DependencyProperty.Register("dwDetail",
            typeof(DataRow), typeof(ViewBase),
            new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OndwDetailChanged));
        public DataRow dwDetail
        {
            get
            {
                return (DataRow)GetValue(dwDetailProperty);
            }
            set
            {
                SetValue(dwDetailProperty, value);
                OnDetailChg(value);
            }
        }
        private static void OndwDetailChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var src = sender as ViewBase;
            if (src != null)
            {
                src.dwDetail = (DataRow)e.NewValue;
            }
        }
        public virtual void OnDetailChg(DataRow _dwDetail)
        {
            if (MV == null)
                return;
            MV.dwDetail = _dwDetail;
        }
        #endregion
        public void Dispose()
        {
            //必须以Dispose(true)方式调用,以true告诉Dispose(bool disposing)函数是被客户直接调用的 
            Dispose(true);
        }
        ~ViewBase()
        {
            Dispose(false);
        }
        public virtual void Dispose(bool disposing)
        {
            // 那么这个方法是被客户直接调用的,告诉垃圾回收器从Finalization队列中清除自己,从而阻止垃圾回收器调用 析构函数 方法. 
            if (disposing)
                GC.SuppressFinalize(this);
        }
        public CollectionViewSource vwMaster
        {
            get
            {
                object source = this.TryFindResource("vwMaster"); if (source == null) return null;
                return (CollectionViewSource)source;
            }
        }

        public CollectionViewSource vwDetail
        {
            get
            {

                object source = this.TryFindResource("vwDetail"); if (source == null) return null;
                return (CollectionViewSource)source;
            }
        }

        public DataRow dwMain
        {
            get
            {
                try
                {
                    dwMaster = null;
                    if (vwMaster.View.CurrentPosition >= 0)
                    {
                        dwMaster = ((DataRowView)vwMaster.View.CurrentItem).Row;
                    }
                }
                catch (Exception ex)
                {
                }
                return dwMaster;
            }
        }


        public ViewBase()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            AllPossible();
            EXPM = new System.Collections.Generic.Dictionary<string, object>();
            ENVPM = new System.Collections.Generic.Dictionary<string, object>();
            EventDispatcher.Instance.OnMessage += wf_OnMessage;
            CompanySetup();
        }
        public virtual void Window_Loaded(object sender, RoutedEventArgs e)
        {

            Selects = "";
            if (IsLoaded)
                return;
            IsLoaded = true;
            if (MV == null)
            {
                MV = this.DataContext as ViewModelBase;
            } 

            if (vwMaster != null)
            {

                TBMain = MV.SetProd.Tables[TB];
                vwMaster.Source = TBMain; 

                if (vwMaster.View != null)
                {
                    vwMaster.View.CurrentChanged += vwMaster_CurrentChanged;
                }
                if (vwDetail != null)
                {
                    vwDetail.Source = TBDetail;
                    if (vwDetail.View != null)
                    {
                        vwDetail.View.CurrentChanged += vwDetail_CurrentChanged;
                    }
                }
            }
            father = Helper.FindVisualTreeRoot(this);
            if (father is DocumentBase)
            {
                RUNID = ((DocumentBase)father).RUNID;
            }
            bgWorker = new BackgroundWorker();
            bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
            bgWorker.RunWorkerCompleted += bgWorker_RunWorkerCompleted;
            AppMode = app.AppMode;
            if (TBMain == null)
                return;
            TBMain.RowChanged += TBMain_RowChanged;

            //SetUpUserRight();
        }

        public virtual void vwMaster_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                if (dwMain == null) //this is impotant
                {

                }
              
                if (SelctionKey.Trim().Length == 0)
                    return;
                if (dwMaster != null)
                {
                    Selects += dwMaster[SelctionKey].ToString() + ";";
                } 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        public virtual void ComboBox_DropDownOpened(object sender, EventArgs e)
        {
            KEY = "";
            if (Counts == 0)
                LOADALL();
        }
        public virtual void btnQuanXuan_Click(object sender, RoutedEventArgs e)
        {
            for (int i = 0; i < ((DataGrid)master).Items.Count; i++)
            {
                var cntr = ((DataGrid)master).ItemContainerGenerator.ContainerFromIndex(i);
                DataGridRow ObjROw = (DataGridRow)cntr;
                if (ObjROw != null)
                {
                    FrameworkElement objElement = ((DataGrid)master).Columns[0].GetCellContent(ObjROw);
                    if (objElement != null)
                    {
                        System.Windows.Controls.CheckBox objChk = (System.Windows.Controls.CheckBox)objElement;
                        if (objChk.IsChecked == false)
                        {
                            objChk.IsChecked = true;
                        }
                    }
                }
            }
        }

        public virtual void vwDetail_CurrentChanged(object sender, EventArgs e)
        {
            try
            {
                dwDetail = null;
                if (vwDetail.View.CurrentPosition >= 0)
                {
                    dwDetail = ((DataRowView)vwDetail.View.CurrentItem).Row;
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        public virtual void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                try
                {
                    IsBusy = false;
                }
                catch (Exception ex)
                {
                    Tracer.Error(ex.StackTrace, ex);
                }
            }));
        }

        public virtual void bgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            this.Dispatcher.Invoke(new Action(() =>
            {
                IsBusy = true;
            }));

        }

        void TBMain_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            try
            {
                if (TBMain.Rows.Count == Counts)
                    return;
                MV.ReSetTBMain();
            }
            catch (Exception ex)
            {

            }
        }


        public virtual void OnWorkflowIDChange(string wfid)
        {
        }
        public int LastMSGID = -1;
        public virtual void OnWorkflowIDChange(MessageEventArgs e)
        {

        }

        public virtual void wf_OnMessage(object sender, MessageEventArgs e)
        {
            if (!IsLoaded)
                return;
            MessageInfo msg = e.Info;
            string src = msg.Sender;
            if (src == null)
                return;
            if (src != "ROOT" && src.Trim() != this.RUNID.Trim())
                return;
            string MSGTYPE = msg.MSGTYPE;

            if (MSGTYPE == null)
                return;
            if (!MESSAGES.Contains(MSGTYPE + ";"))
                return;
            switch (MSGTYPE)
            {
                case "CHAGELVL":
                    if (MV != null)
                    {
                        IsMaster = app.IsMaster;
                        //MV.OnPropertyChanged("IsMaster");
                    }
                    break;
                case "CHGMODE":
                    AppMode = app.AppMode;
                    break;
                case "CHGLANG":
                    LANG = app.LANG;
                    break;
                default:
                    OnWorkflowIDChange(e);
                    break;
            }
        }

        public virtual void Locate(string key, string value)
        {
            if (!IsLoaded)
                return;
            if (vwMaster.View == null)
                return;
            vwMaster.View.MoveCurrentTo(-1);
            if (value == "")
                return;
            if (!TBMain.Columns.Contains(key))
                return;
            //string cfilter = cvMaster.CustomFilter;
            //cvMaster.CustomFilter = null;
            //System.Collections.IEnumerable src = vwMaster.View.SourceCollection;
            string cfilter = ((BindingListCollectionView)vwMaster.View).CustomFilter;
            ((BindingListCollectionView)vwMaster.View).CustomFilter = null;
            filter = "TRIM(" + key + ")='" + value.Trim() + "'";
            rows = TBMain.Select(filter);
            foreach (DataRow row in rows)
            {
                int idx = TBMain.Rows.IndexOf(row);
                vwMaster.View.MoveCurrentToPosition(idx);
                break;
            }
           ((BindingListCollectionView)vwMaster.View).CustomFilter = cfilter;
        }

        public virtual void SelectAllCommand(object sender, RoutedEventArgs e)
        {
            Selects = "";
            foreach (DataRow row in TBMain.Rows)
            {
                Selects += row[SelctionKey].ToString() + ";";
            }
        }

        public virtual void SelectionClearCommand(object sender, RoutedEventArgs e)
        {
            Selects = "";
        }

        public object GetPropertyValue(object item, string property)
        {
            // No value
            object value = null;
            // Get property  from cache
            PropertyInfo pi = null;

            pi = item.GetType().GetProperty(property);
            // If we have a valid property, get the value
            if (pi != null)
                value = pi.GetValue(item, null);
            return value;
        }

        public virtual void OnINFOChg(string info)
        {

            if (MV == null)
                return;
            MV.INFO = info;
        }

        public virtual void New()
        {

        }

        public virtual void Cancel()
        { }

        public virtual void Update()
        { }

        public virtual void Save()
        { }

        public virtual void Delete()
        { }

        public virtual void Next()
        { }

        public virtual void Copy()
        {

        }

        public virtual void NewCommand(object sender, RoutedEventArgs e)
        {

            IsKEY = true;
            IsEdit = true;
            IsSaved = false;
        }

        public virtual void UnSelectCommand(object sender, RoutedEventArgs e)
        {
            Reset();
            IsReset = false;
            IsReset = true;
        }
        public virtual void QueryCommand(object sender, RoutedEventArgs e)
        {
            IsKEY = false;
            IsEdit = false;
            IsQuery = true;
        }

        public virtual void EditCommand(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            ImageBrush brush = btn.Background as ImageBrush;
            if (IsEdit)
            {
                IsKEY = false;
                IsEdit = false;
                if (brush != null)
                {
                    brush.RelativeTransform = null;
                }
                return;
            }
            IsEdit = true;
            IsKEY = false;
            IsSaved = false;
            if (brush != null)
            {
                Helper.RotateImage(btn);
            }
        }

        public virtual void ManageCommand(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            ImageBrush brush = btn.Background as ImageBrush;
            if (IsManage)
            {
                IsManage = false;
                if (brush != null)
                {
                    brush.RelativeTransform = null;
                }
                return;
            }
            IsManage = true;
            if (brush != null)
            {
                Helper.RotateImage(btn);
            }
        }

        public virtual void ForwardCommand(object sender, RoutedEventArgs e)
        {

        }

        public virtual void CancelCommand(object sender, RoutedEventArgs e)
        {

        }

        public virtual void DeleteCommand(object sender, RoutedEventArgs e)
        {
        }

        public virtual void PrintCommand(object sender, RoutedEventArgs e)
        {


        }

        public virtual void DTSTART_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DTSTART = Helpers.Helper.GetDate(sender);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        public virtual void DTEND_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                DTEND = Helpers.Helper.GetDate(sender);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        public virtual void Query_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key != System.Windows.Input.Key.Enter)
                return;
            if (e.Key != System.Windows.Input.Key.Return)
                return;
            this.Focus();
            QueryCommand(sender, e);
        }

        public virtual void InactiveCommand(object sender, RoutedEventArgs e)
        {
            IsInactive = true;
        }

        public virtual void SaveCommand(object sender, RoutedEventArgs e)
        {
            IsEdit = false;
            IsKEY = false;
            IsSaved = true;
        }

        public virtual void ExtendCommand(object sender, RoutedEventArgs e)
        {
            if (MV.IsExtend)
            {
                MV.IsExtend = false;
                return;
            }
            else
            {
                MV.IsExtend = true;
            }
        }

        public virtual void CopyCommand(object sender, RoutedEventArgs e)
        {
            IsKEY = true;
            IsEdit = true;
        }
        int rest = 0;

        public virtual void PrePageCommand(object sender, RoutedEventArgs e)
        {
            MV.PrePage();
        }

        public virtual void NextPageCommand(object sender, RoutedEventArgs e)
        {
            MV.NextPage();
        }

        public void MergeData(DataSet _Set, bool IsMove = true, bool IsClear = true)
        {
            try
            {
                MV.MergeData(_Set, IsMove, IsClear);
                if (!IsMove)
                    return;

                if (vwMaster.View != null)
                {
                    vwMaster.View.MoveCurrentToFirst();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }
        public virtual void SDKEY_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            vwMaster.View.MoveCurrentTo(-1);
        }
        public void ckbSelectedAll_Click(object sender, RoutedEventArgs e)
        {
            if (master == null)
                return;
            if (master is DataGrid)
            {
                ((DataGrid)master).SelectAll();
            }

        }

        public void ckbSelectedAll_Unchecked(object sender, RoutedEventArgs e)
        {
            if (master == null)
                return;
            if (master is DataGrid)
            {
                ((DataGrid)master).UnselectAll();
            }
        }

   

    }
}
